﻿using System.Configuration;
using System.Data;
using System.IO;
using System.Windows;
using KinonekoSoftware.Foundation.Styles;
using KinonekoSoftware.Foundation.UI;
using KinonekoSoftware.Foundation.UI.Core;
using KinonekoSoftware.Foundation.UI.ViewModels;
using KinonekoSoftware.Platform.Core;
using KinonekoSoftware.Studio.ViewModels;
using KinonekoSoftware.UI;

namespace KinonekoSoftware.Studio
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        protected override ShellCore CreateShell() => new AppViewModel();

        protected override ThemeSystem InstallTheming(ForestSetting setting)
        {
            var t = setting.Theme;
            
            //
            //
            if (t == Theme.Custom)
            {
                var fileName = setting.ThemeFileName;

                try
                {

                    if (File.Exists(fileName))
                    {
                        var lines = File.ReadAllLines(fileName);
                        var theme = new CustomThemeSystem(lines);
                        return theme;
                    }

                    //
                    //
                    return new LightThemeSystem();
                }
                catch(Exception ex)
                {
                    Xplat.Error($"启用自定义主题色时发生了错误，{ex.Message}，已修改默认配置。");
                    setting.ThemeFileName = null;
                    setting.Theme         = Theme.Dark;
                    
                    //
                    // 保存设置。
                    Platform.SaveSetting(setting);
                }
            }

            return t == Theme.Dark ? new DarkThemeSystem() : new LightThemeSystem();
        }
        
        protected sealed override ApplicationInformation GetApplicationFolderInformation() => Platform.CreateApplicationInformation();
        protected sealed override ForestSetting GetOrCreateSetting(ApplicationInformation ai) => Platform.GetOrCreateSetting(ai);
        

        protected override void InstallServices()
        {
            Platform.Init();
            
            //
            //
            base.InstallServices();
        }

        protected override void InstallViewAndViewModels()
        {
            var list = new List<MVVMAssociation>(32);
            var impl = new Generators.KinonekoViewAssociationGeneratorGenerated.NClass();
            impl.Register(list);


            foreach (var association in list)
            {
                Xplat.InstallView(association);
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            Platform.Exit();
            base.OnExit(e);
        }
    }
}